package org.easymodelers.gmf.creator.template;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.easymodelers.gmf.GmfModelGenerationException;
import org.easymodelers.gmf.utils.ModelsManager;
import org.easymodelers.modeler.data.ElementDefinition;
import org.easymodelers.modeler.handler.ElementDefinitionHandler;
import org.easymodelers.processing.ModelerUpdate;
import org.easymodelers.template.TemplateHandler;
import org.easymodelers.template.utils.TemplateUtils;
import org.eclipse.emf.ecore.EObject;

public abstract class AbstractTemplateBasedElementDefinitionHandler implements ElementDefinitionHandler {
	private String templateContent;

	public void initializeHandler() {
		this.templateContent = TemplateUtils.loadTemplate(getTemplatePath());
	}
	
	protected abstract String getTemplatePath();
	protected abstract void initializeContextForElementDefinition(
							ElementDefinition definition, Map<String,Object> context);
	protected abstract void initializeTemplateHandler(TemplateHandler templateHandler, ModelsManager modelsManager);
	protected List<ModelerUpdate> getUpdates() {
		return new ArrayList<ModelerUpdate>();
	}
	
	public List<ModelerUpdate> handleElementDefinition(ElementDefinition definition, Object modelsManager, EObject parentEObject) {
		TemplateHandler templateHandler = new TemplateHandler();
		initializeTemplateHandler(templateHandler, (ModelsManager) modelsManager);
		Map<String,Object> context = new HashMap<String, Object>();
		initializeContextForElementDefinition(definition, context);
		templateHandler.setContext(context);
		
		try {
			templateHandler.processTemplate(templateContent);
			return getUpdates();
		} catch (Exception ex) {
			String message = "An error occurs during the model generation with template "+getTemplatePath();
			throw new GmfModelGenerationException(message, ex);
		}
	}


}
